package com.gsm.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.gsm.config.MyException;
import com.gsm.dao.SysRoleDao;
import com.gsm.dao.SysUserDao;
import com.gsm.dto.LoginUserDto;
import com.gsm.entity.RespCode;
import com.gsm.po.SysRole;
import com.gsm.po.SysUser;
import com.gsm.service.LoginService;
import com.gsm.utils.JwtUtils;
import com.gsm.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public LoginUserVo selectUserInfo(LoginUserDto dto) {
        //根据手机号查询用户
        SysUser sysUser = sysUserDao.selectSysUserByIphoneNo(dto.getIphoneNo());
        if (sysUser == null) {
            throw new MyException(RespCode.REG_NAME_NOT_EXIST_ERROR);
        }
        //判断密码是否相同
        String pc = dto.getPc();
        String pc1 = sysUser.getPc();
        Boolean bool = passwordEncoder.matches(pc, pc1);
        if(!bool){
            throw new MyException(RespCode.LOGIN_NAME_OR_PWD_ERROR);
        }
        sysUser.setPo(null);
        sysUser.setPc(null);
        //查询用户角色
        List<SysRole> sysRoles = sysRoleDao.selectSysRoleListByUserId(sysUser.getUserId());
        sysUser.setSysRoles(sysRoles);
        //生成Token
        Map<String, String> map = new HashMap<>();
        sysRoles.forEach(i->{
            map.put(i.getRoleId().toString(),i.getRoleName());
        });
        String token = jwtUtils.getJwt(sysUser.getUserId().toString(), sysUser.getUserName(), map);
        //封装返回
        LoginUserVo loginUserVo = LoginUserVo.builder()
                .token(token)
                .sysUser(sysUser)
                .build();
        return loginUserVo;
    }
}
